<?php
//文章管理
namespace App\Http\Controllers\App\Content;

use App\Http\Requests\ArticleRequest;
use App\Http\Services\Elasticsearch;
use App\Models\Article;
use App\Models\ArticleCategory;
use App\Models\Tag;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ArticleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return
     */
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $model = Article::query();
            if ($request->has('category_id')) {
                $model = $model->where('category_id', $request->get('category_id'));
            }
            if ($request->has('title')) {
                $model = $model->where('title', 'like', '%' . $request->get('title') . '%');
            }
            $res = $model->orderBy('created_at', 'desc')->with(['tags', 'category'])->paginate($request->get('limit', 30))->toArray();
            return [
                'code'  => 0,
                'msg'   => 'Success',
                'count' => $res['total'],
                'data'  => $res['data']
            ];
        }

        //分类
        $categories = ArticleCategory::with('allChilds')->where('parent_id', 0)->orderBy('sort', 'desc')->get();
        return view('app.content.list', compact('categories'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //分类
        $categories = ArticleCategory::with('allChilds')->where('parent_id', 0)->orderBy('sort', 'desc')->get();
        //标签
        $tags = Tag::get();
        return view('app.content.listform', compact('tags', 'categories'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(ArticleRequest $request)
    {
        $data    = $request->only(['category_id', 'title', 'keywords', 'description', 'content', 'thumb', 'click']);
        $article = Article::create($data);
        if ($article && !empty($request->get('tags'))) {
            $article->tags()->sync($request->get('tags'));
        }

        // es数据的添加
        //$es   = new Elasticsearch('article', '_doc');
        //$body = [
        //    'title'    => $article->title,
        //    'keywords' => $article->keywords,
        //];
        //$es->updateIndex($article->id, $body);

        return ['code'=>0, 'msg' => '添加成功'];
    }

    // 生成索引
    public function esinit()
    {
        $es  = new Elasticsearch('article', '_doc');
        $arr = [
            'title'    => [
                // 相当于数据查询是的 = 张三你好，必须找到张三你好
                'type' => 'keyword'
            ],
            'keywords' => [
                'type'            => 'text',
                // 中文分词  张三你好   张三  你好 张三你好
                'analyzer'        => 'ik_max_word',
                'search_analyzer' => 'ik_max_word'
            ]
        ];
        return $es->createIndex($arr);
    }

    /**
     * Display the specified resource.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $article = Article::with('tags')->findOrFail($id);
        if (!$article) {
            return redirect(route('admin.article'))->withErrors(['status' => '文章不存在']);
        }
        //分类
        $categories = ArticleCategory::with('allChilds')->where('parent_id', 0)->orderBy('sort', 'desc')->get();
        //标签
        $tags = Tag::get();
        foreach ($tags as $tag) {
            $tag->checked = $article->tags->contains($tag) ? 'checked' : '';
        }
        return view('app.content.listform', compact('article', 'categories', 'tags'));

    }

    /**
     * Update the specified resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @param int $id
     * @return
     */
    public function update(ArticleRequest $request, $id)
    {
        $article = Article::with('tags')->findOrFail($id);
        $data    = $request->only(['category_id', 'title', 'keywords', 'description', 'content', 'thumb', 'click']);
        if ($article->update($data)) {
            $article->tags()->sync($request->get('tags', []));
            return $this->success('更新成功');
        }
        return $this->error('系统错误');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $ids = $request->get('ids');
        if (empty($ids)) {
            return response()->json(['code' => 1, 'msg' => '请选择删除项']);
        }
        foreach (Article::whereIn('id', $ids)->get() as $model) {
            //清除中间表数据
            $model->tags()->sync([]);
            //删除文章
            $model->delete();
        }
        return response()->json(['code' => 0, 'msg' => '删除成功']);
    }

}
